﻿using MongoDB.Bson;
using MongoDB.Driver;
using SupermarkedModel;
using System;
using System.Linq;
using System.Xml;

namespace Supermarket.Client
{
    internal class XMLReadSave
    {
        public static void LoadSaveVendorExpencesInMongo()
        {
            SupermarketDbEntities entities = new SupermarketDbEntities();

            MongoClient mongoClient = new MongoClient("mongodb://localhost/");
            MongoServer mongoServer = mongoClient.GetServer();
            MongoDatabase db = mongoServer.GetDatabase("SupermarketDB");
            MongoCollection<BsonDocument> vendorExpensesCollection = db.GetCollection("VendorExpenses");

            using (XmlReader reader = XmlReader.Create("../../Vendors-Expenses.xml"))
            {
                int currentVendorId = 0;
                DateTime currentMonth;
                decimal currentExpenses;

                while (reader.Read())
                {
                    string vendorName = String.Empty;
                    if (reader.Name == "sale" && reader.GetAttribute("vendor") != null)
                    {
                        vendorName = reader.GetAttribute("vendor");

                        currentVendorId = (from v in entities.Vendors
                                           where v.VendorName == vendorName
                                           select v.VendorID).FirstOrDefault();
                    }

                    if (reader.Name == "expenses")
                    {
                        currentMonth = DateTime.Parse(reader.GetAttribute("month"));
                        currentExpenses = reader.ReadElementContentAsDecimal();
                        entities.VendorExpenses.Add(new VendorExpens()
                        {
                            Month = currentMonth,
                            Expenses = currentExpenses,
                            VendorID = currentVendorId
                        });

                        vendorExpensesCollection.Insert(new BsonDocument { { "vendor-name", vendorName }, { "expenses", currentExpenses.ToString() }, { "month", currentMonth.ToString() } });
                    }
                }
            }

            entities.SaveChanges();
        }
    }
}
